package com.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.constants.Constant;
import com.test.pojo.TbUser;
import com.test.mapper.TbUserMapper;
import com.test.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yanglijun
 * @since 2020-12-12
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {
    @Resource
    private TbUserMapper tbUserMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public String login(TbUser tbUser) {

        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",tbUser.getUsername());
        TbUser loginUser = tbUserMapper.selectOne(queryWrapper);
        System.out.println(loginUser);
        if (loginUser!=null && loginUser.getPassword().equals(tbUser.getPassword())) {
            //登录成功
            String val = JSON.toJSONString(loginUser);

            String key= Constant.REDIS_USER_KEY_PREFIX+loginUser.getUsername();
            try {
                redisTemplate.opsForValue().set(key,val,1800, TimeUnit.SECONDS);
                System.out.println(key+val);
                return key;
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }
}
